<template>
  <div>
    <Navbar :appTitle="appTitle" :rtitle="(!showGoodsPicker && !isShowLatticeNotification) ? '打印' : ''" @ClickRight="onClickRight"/>
    <div
      class="form-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <div class="d-head">
        <div class="content">
          <div class="left">
            <div class="title"style="max-width: 6rem;">{{ buildForm.shelvesTaskCode || '-' }}</div>
            <div class="row" style="color:#191f25; display: flex;flex-direction: row;">
              <span style="width: 2.7rem;">入库任务编号：</span>
              <span style="max-width: 4.5rem;overflow: hidden;text-overflow: ellipsis;">{{buildForm.inboundTaskCode || "-"}}</span>
            </div>
            <div class="row">
              <span style="color:#191f25">业务类型：{{buildForm.inboundTaskTypeText || "-"}}</span>
            </div>
          </div>
          <div class="right">
            <div class="row warining">
              待上架：
              <span>{{buildForm.unShelvedNum}}</span>
            </div>
            <div class="row success" @click="toDetail">
              已上架：
              <span>{{buildForm.shelvedNum}}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="tabs-contain"  v-if="entryDetails && entryDetails.length != 0">
        <van-tabs @change="tabChange" v-model:active="active" color="#1989fa" line-height="0.01rem" line-width="3.5rem" title-active-color="#108ee9" swipe-threshold="3">
          <van-tab v-for="(item, index) in entryDetails" :title="item.goodsName" title-class="tab-wrap-ano">
            <div class="list" >
              <div class="wrap">
                <div class="top">
                  <div class="title titleWidth">
                    {{ item.goodsCode	 }} | {{ item.goodsName }} | {{ item.goodsSpec }}
                  </div>
                </div>
                <div class="center">
                  <div>
                    <p>
                      <span class="key">包装规格：</span>
                      <span class="value">{{ item.packageSpec	}}</span>
                    </p>
                    <p>
                      <span class="key">产地：</span>
                      <span class="value">{{ item.address	}}</span>
                    </p>
                    <p>
                      <span class="key">待上架/收货数量：</span>
                      <span class="value">{{ item.unShelvedNumText	}} / {{ item.receiptedNumText	}}</span>
                    </p>
                    <p style="margin-top: 8px;">
                      <van-tag color="#e8f4ff" text-color="#1890ff">{{ item.produceDate	}}</van-tag>
                      <van-tag style="max-width: 1.5rem; overflow: hidden; text-overflow: ellipsis;" color="#e8f4ff" text-color="#1890ff">{{ item.batchCode	}}</van-tag>
                      <van-tag color="#e8f4ff" text-color="#1890ff">{{ item.unitName	}}</van-tag>
                      <span
                        style="flex: 1; text-align: right; color: rgb(24, 144, 255);"
                        @click="btnPrint(item.taskId, item.detailId)"
                      >打印</span>
                    </p>
                  </div>
                </div>

                <div style="height: 6px; background-color: #f3f3f3; width: 100%;"></div>

                <div class="list" >
                  <div class="wrap"
                    v-for="(p, i) in item.inLatticeDtoList"
                    :key="p.latticeId"
                    v-show="item.inLatticeDtoList.length != 0"
                  >
                    <van-cell-group>
                      <p class="label otherText">
                        <span>库位（{{ i + 1 }}）</span>
                        <span class="deleteStyle" :style="{'color': item.inLatticeDtoList.length == 1 ?'#5a5a5a':'#ff4d4f' }" @click="deleteLattice(i, item.inLatticeDtoList.length)">删除</span>
                      </p>
                      <div class="bottomLine"></div>
                      <van-cell-group class="formItemFlex">
                        <p class="label FormTit">上架库位</p>
                        <div class="haveUnitBox">
                          <van-field
                            v-model="p.latticeFullName"
                            placeholder="请选择或扫码"
                            input-align="right"
                            readOnly
                            @click="showLatticeNotification(index, i)"
                          >
                          <template #right-icon>
                            <div style="display: flex;">
                              <van-icon
                                @click="showLatticeNotification(index, i)"
                                size="20"
                                color="#999"
                                name="arrow"
                                style="margin-top: 2px"
                              />
                              <van-icon
                                @click.stop="clickCode(index, i, false)"
                                size="20"
                                color="#999"
                                name="scan"
                                style="margin-top: 2px"
                              />
                            </div>
                          </template>
                          </van-field>
                        </div>
                      </van-cell-group>
                      <div class="bottomLine"></div>
                      <van-cell-group class="formItemFlex">
                        <p class="label FormTit">上架数量</p>
                        <div class="haveUnitBox">
                          <van-field
                            v-model="p.shelvedNum"
                            type="number"
                            placeholder="请输入"
                            input-align="right"
                            :formatter="(e) => clearNoNum(e, item.unShelvedNum)"
                          >
                            <template #right-icon>
                              <span>{{ item.unitName || '' }}</span>
                            </template>
                          </van-field>
                        </div>
                      </van-cell-group>
                    </van-cell-group>
                    <div style="height: 6px; background-color: #f3f3f3; width: 100%;"></div>
                  </div>
                  <div class="addGoodScontain">
                    <div class="addgoods" style="border-right: 1px solid #f2f2f2;" @click="showLatticeNotification(index)">
                      <van-icon name="plus" size="16px" color="#1890ff" style="top: 2px" />
                      <a>库位</a>
                    </div>
                    <div class="addgoods" @click="clickCode(index, null, true)">
                      <van-icon name="scan" size="16px" color="#1890ff" style="top: 2px"/>
                      <a>扫库位码</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </van-tab>
        </van-tabs>
        <div class="all-down-btn" v-show="entryDetails.length > 3">
          <p @click="openDropDownModel">
            <span>全部</span>
            <span>
              <van-icon name="arrow-down" color="#1989fa" size="16"/>
            </span>
          </p>
        </div>
        <div class="all-down-model" v-show="allDownShow">
            <div class="tags-contain">
              <span
                class="goodsNameTag"
                v-for="(item, index) in  entryDetails"
                @click="clickGoodsNames(index)"
                :style="{color: index == active ? '#1890ff' : '#333333' }"
              >
                {{ item.goodsName }}
              </span>
            </div>
            <div class="ctrBtn-contian">
              <span @click="closeDropDownModel">关闭</span>
              <span>
                <van-icon name="arrow-up" color="#1989fa" size="16"/>
              </span>
            </div>
        </div>
      </div>
      <van-empty v-else description="物品明细为空" />

      <div class="search-bottoms">
        <van-button class="btncancle" :loading="subLoading" loading-text="提交中..." @click="btnConfirm(true)">提交并打印</van-button>
        <van-button class="btnconfirm" :loading="subLoading" loading-text="提交中..." @click="btnConfirm(false)">提交</van-button>
      </div>
    </div>
    <!--选择库位 -->
    <binLocation-pickers-ak
      v-if="isShowLatticeNotification"
      :listUrl="latticeNotificationUrl"
      :columns="latticeNotificationgColumns"
      :checkedShow="recentLatIndex == -1 ? true :  false"
      :selectedGoods="recentLatIndex == -1 ? entryDetails[recentGoodsIndex]['inLatticeDtoList'] : []"
      @getCheckedValue="getCheckedValue"
      @handleList="handleList"
    ></binLocation-pickers-ak>
    <!--选择物品 - 打印相关 -->
    <goods-pickers-ak
      v-if="showGoodsPicker"
      :listUrl="goodslistUrl"
      :columns="goodsColumns"
      :selectedGoods="checkedGoods"
      @getCheckedGoods="getCheckedGoodsIds"
      :isPrint="true"
      :idKey="'unShelvedNum'"
    ></goods-pickers-ak>
    <!-- 浏览器扫码组件 -->
    <qrcode
      :qrcode="codeForm.qrcode"
      :showClose="codeForm.showClose"
      v-show="codeForm.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- 激光扫码组件 -->
    <PDAsao @changeScan="changeScan2" />
     <!-- 批量扫码弹窗 -->
    <van-popup
      v-model="isshow"
      :overlay="false"
      position="bottom"
      :style="{ height: '50%' }"
      :close-on-click-overlay="false"
      v-if="entryDetails.length != 0 && qrlatticeNotification.length != 0"
    >
      <div class="qrcodeModel">
        <div class="nav_contain">
        <span class="left" @click="modelClose">
          <van-icon :size="20" color="#3ba1ff" name="arrow-left" />
        </span>
        <span class="center">
          上架库位
        </span>
        <span class="right" @click="modelCofirm">
          确定
        </span>
        </div>
        <div class="goodsInfo">
          <div class="wrap">
            <div class="top">
              <div class="title titleWidth">
                {{ entryDetails[recentGoodsIndex].goodsCode	 }} |
                {{ entryDetails[recentGoodsIndex].goodsName }} |
                {{ entryDetails[recentGoodsIndex].spec }}
              </div>
            </div>
            <div class="center">
              <div>
                <p>
                  <span class="key">产地：</span>
                  <span class="value">{{ entryDetails[recentGoodsIndex].address	}}</span>
                </p>
                <p>
                  <span class="key">包装规格：</span>
                  <span class="value">{{ entryDetails[recentGoodsIndex].packageSpec	}}</span>
                </p>
                <p>
                  <van-tag color="#e8f4ff" text-color="#1890ff">{{ entryDetails[recentGoodsIndex].produceDate	}}</van-tag>
                  <van-tag color="#e8f4ff" text-color="#1890ff">{{ entryDetails[recentGoodsIndex].batchCode	}}</van-tag>
                  <van-tag style="width: 42px;" color="#e8f4ff" text-color="#1890ff">{{ entryDetails[recentGoodsIndex].unitName	}}</van-tag>
                </p>
              </div>
              <div class="totalContain" :style="{'width': qrlatticeNotificationTotal.length > 6 ? '145px' : '105px'}">
                <p style="height: 24px;"></p>
                <p>已选{{ qrlatticeNotification.length || 0 }}</p>
                <p>上架合计{{ qrlatticeNotificationTotal || 0 }}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="list">
          <div class="wrap"
            v-for="(p, i) in qrlatticeNotification"
            :key="p.latticeId"
          >
            <van-cell-group>
              <p class="label otherText">
                <span style="border-left: 4px solid #40a9ff;">
                  {{ p.latticeFullName }}
                </span>
                <span
                class="deleteStyle"
                :style="{'color':'#ff4d4f' }"
                @click="deleteLatticeInmodel(i)"
                >删除</span>
              </p>
              <div class="bottomLine"></div>
              <van-cell-group class="formItemFlex">
                <p class="label FormTit">上架数量</p>
                <div class="haveUnitBox">
                  <van-field
                    v-model="p.shelvedNum"
                    type="number"
                    placeholder="请输入"
                    input-align="right"
                    :formatter="(e) => clearNoNum(e, entryDetails[recentGoodsIndex].unShelvedNum)"
                  >
                    <template #right-icon>
                      <span>{{ entryDetails[recentGoodsIndex].unitName || '' }}</span>
                    </template>
                  </van-field>
                </div>
              </van-cell-group>
            </van-cell-group>
            <div style="height: 6px; background-color: #f3f3f3; width: 100%;"></div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import {
  shelvesTaskDetail,
  shelvedGoods,
  getWarehouseLatticeDetail
} from "@/api/inventoryOrder";
import store from "@/store";
import BinLocationPickersAk from "@/components/choiceuse/BinLocationPickersAk";
import GoodsPickersAk from "@/components/choiceuse/GoodsPickersAk";
import PDAsao from "@/components/scanCode/PDAsao.vue";
import Decimal from 'decimal.js';

export default {
  name: "shelfTaskForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    BinLocationPickersAk,
    GoodsPickersAk,
    qrcode: () => import("@/components/scanCode"),
    PDAsao
  },
  data() {
    return {
      appTitle: "上架",
      buildForm: {
        shelvesTaskId: '',
        shelvesTaskCode: "",
        inboundTaskId: "",
        inboundTaskCode: "",
        inboundTaskType: "",
        inboundTaskTypeText: "",
        unShelvedNum: "",
        shelvedNum:''
      },
      entryDetails:[],
      recentGoodsIndex: 0,
      active: '',
      allDownShow: false,
      isShowLatticeNotification: false,
      latticeNotificationUrl: "/wmslattice/getLatticeNotification",
      latticeNotificationgColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "库位物品",
            key: ["goodsNameTxt"],
          },
          {
            name: "物品数量",
            key: ["goodsNumTxt"],
          },
          {
            name: "物品总数量",
            key: ["totalNum"],
          },
          { // 多选时调用
            name: "上架数量",
            key: ["shelvedNum"],
            type: 'input',
            unit: 'unitName'
          },
        ],
        labelKey: [], //标签
        operationText: "",
        usedBy: "shelfTaskForm",
      },
      showGoodsPicker: false,
      goodslistUrl: "/inbound/shelvesTask/shelvedInfoListByGoods",
      goodsColumns: {
        titleKey: ['goodsCode', 'goodsName', 'goodsSpec'], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "待上架",
            key: ["unShelvedNumText"],
          },
        ],
        labelKey:['produceDate', 'batchCode', 'unitName'],
        operationText: "",
      },
      checkedGoods: [],
      isToPrint: false,
      recentLatIndex: -1,
      // 扫码相关
      codeForm: {
        qrcode: false,
        showClose: false,
      },
      torchActive: true,
      camera: "off",
      isshow: false,
      qrlatticeNotification: [],
      subLoading: false
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.isShowLatticeNotification || this.showGoodsPicker) {
      this.isShowLatticeNotification = false;
      this.showGoodsPicker = false
      this.appTitle = '上架';
      next(false);
    } else {
      next();
    }
  },
  async created() {
    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    this.initData();
  },
  computed: {
    qrlatticeNotificationTotal() {
      // 确保 qrlatticeNotification 是数组类型，并且数组不为空
      if (!Array.isArray(this.qrlatticeNotification) || this.qrlatticeNotification.length === 0) {
        return 0; // 如果不满足条件，直接返回 0
      }

      // 使用数组的 reduce 方法来累加 goodsNum，如果 goodsNum 不存在则默认为 0
      return this.qrlatticeNotification.reduce((accumulator, currentNotification) => {
        // 确保 currentNotification.goodsNum 存在且为数字类型
        const shelvedNum = typeof currentNotification.shelvedNum === 'number' ? currentNotification.shelvedNum : Number(currentNotification.shelvedNum);
        return new Decimal(shelvedNum).plus(accumulator).toString();
      }, 0);
    },
  },
  methods: {
    tabChange(name, title) {
      this.recentGoodsIndex = name
    },
    closeModel() {
      this.isshow = false
      this.turnCameraOff()
    },
    onClickRight() {
      this.goodslistUrl = `/inbound/shelvesTask/queryDetailPageList?shelvesTaskId=${this.buildForm.shelvesTaskId}`
      this.appTitle = '选择打印物品';
      this.showGoodsPicker = true
    },
    getCheckedGoodsIds(list) {
      this.checkedGoods = list
      this.appTitle = '上架';
      this.showGoodsPicker = false
      let keys = list.map((ele) => {
        return ele.detailId
      })
      this.btnPrint(this.buildForm.shelvesTaskId, keys.join(','))
    },
    //已收货
    toDetail() {
      this.$router.push({
        path: "/shelfTaskGoodsDetail",
        query: {
          id: this.buildForm.shelvesTaskId,
        },
      });
    },
    // 确认选中库位 多选
    async getCheckedValue(list) {
      if(this.recentLatIndex != -1) {
        return
      }
      this.isShowLatticeNotification = false;
      this.appTitle = "上架";

      this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'] = list.map((son) => {
        let recIndex = this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'].findIndex((ele) =>ele.latticeId == son.id)

        if(recIndex != -1) {
          let recObj = this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'][recIndex]
          recObj['shelvedNum'] = son['shelvedNum']
          return recObj
        }else {
          let { id, latticeCode, latticeName, shelvedNum } = son
          return {
            latticeId: id,
            latticeCode: latticeCode,
            latticeName: latticeName,
            latticeFullName: latticeCode + '|' + latticeName,
            shelvedNum: shelvedNum || this.entryDetails[this.recentGoodsIndex]['unShelvedNum']
          };
        }
      });
    },
    // 确认选中库位 单选
    handleList(binLocationid, item, text) {
      if(this.recentLatIndex == -1) {
        return
      }
      this.isShowLatticeNotification = false;
      this.appTitle = "上架";

      let isValidated = true;
      try {
        this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'].forEach((ele) => {
          if(ele.latticeId == item.id) {
            this.isValidated = false
            throw new Error(`该库位已存在`);
          }
        })
        if (!isValidated) {
          return;
        }
      } catch(error) {
        this.$toast(error.message);
        return false;
      }

      let { id, latticeCode, latticeName } = item
      this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'][this.recentLatIndex] = {
        latticeId: id,
        latticeCode: latticeCode,
        latticeName: latticeName,
        latticeFullName: latticeCode + '|' + latticeName,
        shelvedNum: this.entryDetails[this.recentGoodsIndex]['unShelvedNum']
      }
    },
    // 库位选择
    showLatticeNotification(index, rclIndex) {
      this.recentGoodsIndex = index
      if(rclIndex != undefined) { // 单选
        this.recentLatIndex = rclIndex

        this.latticeNotificationgColumns.content = [
          {
            name: "库位物品",
            key: ["goodsNameTxt"],
          },
          {
            name: "物品数量",
            key: ["goodsNumTxt"],
          },
          {
            name: "物品总数量",
            key: ["totalNum"],
          },
        ]
      }else { // 多选
        this.recentLatIndex = -1
        this.latticeNotificationgColumns.content = [
          {
            name: "库位物品",
            key: ["goodsNameTxt"],
          },
          {
            name: "物品数量",
            key: ["goodsNumTxt"],
          },
          {
            name: "物品总数量",
            key: ["totalNum"],
          },
          {
            name: "上架数量",
            key: ["shelvedNum"],
            type: 'input',
            unit: 'unitName'
          },
        ]
      }
      this.appTitle = '库位';
      this.isShowLatticeNotification = true
    },
    // 删除库位
    deleteLattice(index, recListLength) {
      if(recListLength == 1) {
        return
      }
      this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'].splice(index, 1);
    },
    // tag 弹出层相关功能
    openDropDownModel() {
      this.allDownShow = true
    },
    closeDropDownModel() {
      this.allDownShow = false
    },
    clickGoodsNames(index) {
      this.active = index
      this.allDownShow = false
    },

    // 重置form表单
    resetForm () {
      this.buildForm = {
        shelvesTaskId: '',
        shelvesTaskCode: "",
        inboundTaskId: "",
        inboundTaskCode: "",
        inboundTaskType: "",
        inboundTaskTypeText: "",
        unShelvedNum: "",
        shelvedNum:''
      }
      this.recentGoodsIndex = 0
      this.entryDetails = []
      this.active = ''
      this.recentLatIndex = -1
      this.checkedGoods = []
    },
    // 提交
    btnConfirm(isToPrint) {
      this.isToPrint = isToPrint
      let isValidated = true;
      try {
        // 上架物品明细 为空 选项名称、数量 表单验证
        if (this.entryDetails && this.entryDetails.length > 0) {
          this.entryDetails.forEach((element, index) => {
            if (element.goodsId) {
              if(element.inLatticeDtoList && element.inLatticeDtoList.length > 0) {
                let shelvedNums = 0 // 库位 上架数量总量
                element.inLatticeDtoList.forEach((ele, i) => {
                  if((ele.latticeId && ele.latticeId != "") && (ele.shelvedNum && ele.shelvedNum != "")) {
                    shelvedNums += Number(ele.shelvedNum)
                    if (ele.shelvedNum == 0) {
                      isValidated = false;
                      throw new Error(`物品（${element.goodsName}）库位（${i + 1}） 上架数量不可为零`);
                    }
                  }else {
                    throw new Error(`物品（${element.goodsName}）上架库位（${i + 1}） 不可为空！`);
                  }
                })
                if (shelvedNums > element.unShelvedNum) {
                  isValidated = false;
                  throw new Error(`物品（${element.goodsName}） 上架总量不可大于物品待上架数量`);
                }
              }
            } else {
              isValidated = false;
              throw new Error(`请选择物品`);
            }
          });
        } else {
          isValidated = false;
          throw new Error(`请选择物品`);
        }

        if (!isValidated) {
          return;
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      let subList = []
      this.entryDetails.forEach((element, index) => {
        if (element.goodsId) {
          if(element.inLatticeDtoList && element.inLatticeDtoList.length > 0) {
            let canSubmit = true
            element.inLatticeDtoList.forEach((ele, i) => {
              if(ele.latticeId == "" || ele.shelvedNum == "") {
                canSubmit = false
              }
            })
            if(canSubmit) {
              subList.push(element)
            }
          }
        }
      });

      if(subList.length != 0) {
        this.handleSubmit(subList);
      }
    },
    handleSubmit(subList) {
      let {shelvesTaskId, inboundTaskType} = this.buildForm

      let params = {
        taskId: shelvesTaskId,
        inboundTaskType: inboundTaskType,
        goodsDtoList: subList.map((ele) => {
          return {
            taskDetailId: ele.detailId,
            goodsBatchId: ele.goodsBatchId,
            goodsId: ele.goodsId,
            batchCode: ele.batchCode,
            produceDate: ele.produceDate,
            latticeDtoList: ele.inLatticeDtoList.map((ele2) => {
              return {
                latticeId: ele2.latticeId,
                shelvedNum: ele2.shelvedNum
              }
            })
          };
        }),
      };
      this.subLoading = true
      shelvedGoods(params).then((res) => {
        if (res.success) {
          this.$toast(res.message);
          if(this.isToPrint) {
            this.btnPrint(res.result.operateId)
          }else {
            this.initData()
          }
        } else {
          this.$toast(res.message);
        }
        this.subLoading = false
      }).catch(() => {
        this.subLoading = false
      }).finally(() => {
        this.subLoading = false
      })
    },
    // 打印
    btnPrint(id, detailId) {
      this.$router.push({
        path: "/shelfTaskPrintList",
        query: {
          id: id,
          detailId: detailId
        }
      });
    },
    // 初始化页面数据
    initData() {
      let id = this.$route.query.id;

      this.resetForm()
      if(id) {
        this.appTitle = "上架";
        // 上架详情 基本信息、关联物品
        shelvesTaskDetail({taskId: id}).then((res) => {
          if (res.code == 200 && res.result) {
            this.buildForm = res.result;

            this.entryDetails = res.result.unShelvedGoodsList.map((son) => {
              let { latticeId, latticeCode, latticeName, unShelvedNum } = son
              return {
                ...son,
                inLatticeDtoList: [
                  {
                    latticeId: latticeId || '',
                    latticeCode: latticeCode || '',
                    latticeName: latticeName || '',
                    latticeFullName: (latticeCode && latticeName) ? latticeCode + '|' + latticeName : '',
                    shelvedNum: unShelvedNum || ''
                  }
                ]
              };
            });

          } else {
            this.$toast(res.message);
          }
        });
      }
    },
    /*上架数量 处理*/
    clearNoNum(value, maxValue) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = "0";
      }
      //输入长度控制
      if (value > 99999999999999.9999) {
        value = '';
      }
      //最大值限制
      if (Number(value) > maxValue) {
        value = ''
      }
      return value;
    },
    // 扫码相关
    // 打开相机
    clickCode(index, cIndex, isshow) {
      let that = this;
      this.recentGoodsIndex = index
      this.recentLatIndex = cIndex
      this.isshow = isshow
      // return
      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.codeForm.qrcode = true;
          that.camera = "rear";
          break;
        case "dingding":
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    // 扫码结果回调
    onDecode(result) {
      // result, 扫描结果，可以根据自己的需求来实现相应的功能
      this.codeForm.code = JSON.parse(result);
      if (this.codeForm.code.EntityType == "lattice" && this.codeForm.code.id) {
        // 库位二维码
        getWarehouseLatticeDetail(this.codeForm.code.id).then((res) => {
          if(res.code == 200 && res.result) {
            if(res.result.status == 'effective') {

              try {
                this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'].forEach((ele) => {
                  if(ele.latticeId == res.result.id) {
                    throw new Error(`该库位已存在`);
                  }
                })

                if(this.qrlatticeNotification.length != 0) {
                  this.qrlatticeNotification.forEach((ele) => {
                    if(ele.latticeId == res.result.id) {
                      throw new Error(`该库位已存在`);
                    }
                  })
                }

              } catch(error) {
                this.$toast(error.message);
                return false;
              }

              if(this.isshow) { // 批量扫码-库位
                let { id, latticeCode, latticeName } = res.result
                let recLength = this.qrlatticeNotification.length

                this.$set(this.qrlatticeNotification, recLength, {
                  latticeId: id,
                  latticeCode: latticeCode,
                  latticeName: latticeName,
                  latticeFullName: latticeCode + '|' + latticeName,
                  shelvedNum: ''
                })
              } else { // 单个扫码-库位
                let { id, latticeCode, latticeName } = res.result
                this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'][this.recentLatIndex] = {
                  latticeId: id,
                  latticeCode: latticeCode,
                  latticeName: latticeName,
                  latticeFullName: latticeCode + '|' + latticeName,
                  shelvedNum: this.entryDetails[this.recentGoodsIndex]['unShelvedNum']
                }
                this.turnCameraOff()
              }
            }else {
              this.$toast("该库位已被禁用");
              this.clickCode(this.recentGoodsIndex);
            }
          }
        })
      } else {
        this.$toast("请扫正确二维码");
        this.clickCode(this.recentGoodsIndex);
      }
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.codeForm.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },
    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
    // 激光扫码
    changeScan2(v) {
      if (v.EntityType == "goods") {
        getWarehouseLatticeDetail(v.id).then((res) => {
          if(res.code == 200 && res.result) {
              if(res.result.status == 'effective') {
                let { id, latticeCode, latticeName } = res.result
                let recLatIndex = this.entryDetails[this.active]['inLatticeDtoList'].findIndex((ele) => ele.latticeId == id)
                if(recLatIndex == -1) {
                  let obj = {
                    latticeId: id,
                    latticeCode: latticeCode,
                    latticeName: latticeName,
                    latticeFullName: latticeCode + '|' + latticeName,
                    shelvedNum: this.entryDetails[this.active]['unShelvedNum']
                  }
                  this.entryDetails[this.active]['inLatticeDtoList'].push(obj)
                }else {
                  this.$toast("该库位已存在");
                }
            }else {
              this.$toast("该库位处于禁用状态");
            }
          }else {
            this.$toast("数据异常");
          }
        })
      }
    },
    // 批量扫码弹窗 确定
    modelCofirm() {
      let recDtoList = this.entryDetails[this.recentGoodsIndex]['inLatticeDtoList'].concat(this.qrlatticeNotification)
      this.$set(this.entryDetails[this.recentGoodsIndex], 'inLatticeDtoList', recDtoList)

      this.isshow = false
      this.qrlatticeNotification = []
      this.turnCameraOff()
    },
    // 批量扫码弹窗 关闭
    modelClose() {
      this.qrlatticeNotification = []
      this.isshow = false
      this.turnCameraOff()
    },
    // 删除库位
    deleteLatticeInmodel(index) {
      this.qrlatticeNotification.splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.tabs-contain {
  position: relative;

  /deep/.van-tabs__nav--line.van-tabs__nav--complete {
    width: calc(100% - 1.6rem);
  }
  /deep/.van-tabs__wrap--scrollable .van-tab {
    width: 33%;
    min-width: 230px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .all-down-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 120px;
    height: 90px;
    font-size: 28px;
    color: rgb(25, 137, 250);
    line-height: 90px;
    text-align: center;
    background-color: #fff;
    /deep/.van-icon {
      top: 6px;
    }
  }
  .all-down-model {
    position: absolute;
    top: 0;
    right: 0;
    width: 100vw;
    background-color: #fff;
    z-index: 9;
    border-bottom: 1px solid #f3f3f3;
    padding: 6px;
    .tags-contain {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
      .goodsNameTag {
        width: 22%;
        margin: 10px 10px;
        padding: 5px 20px;
        background-color: #f3f3f3;
        color: #333333;
        border-radius: 5px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        text-align: center;
        height: 60px;
        line-height: 42px;
      }
    }
    .ctrBtn-contian {
      height: 50px;
      text-align: center;
      color: #1890ff;
      font-size: 24px;
      line-height: 50px;
      /deep/.van-icon {
        top: 6px;
      }
    }
  }
}
.qrcodeModel{
  background-color: rgb(243, 243, 243);
  .nav_contain {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ceced1;
    padding: 24px 20px 10px;
    position: fixed;
    width: 100vw;
    z-index: 2006;
    background: #fff;
    span {
      font-size: 32px;
    }
    .left {
      color: #3ba1ff;
    }
    .center {
      color: #191f25;
      font-weight: bolder;
    }
    .right {
      color: #3ba1ff;
    }
  }
  .goodsInfo {
    position: relative;
    top: 90px;
    margin-top: 0;
    .wrap {
      background: #fff;
      width: 100vw;
      .otherText {
        display: flex;
        justify-content: space-between;
        font-size: 32px;
        color: #191f25;
        margin: 0;
        font-weight: 500;
        .deleteStyle {
          font-weight: 400;
          color: #ff4d4f
        }
      }
      .top {
        display: flex;
        justify-content: flex-start;
        padding-top: 10px;
        .icon {
          width: 6px;
          height: 32px;
          background: #1890ff;
          margin: 6px 10px 0 10px;
        }
        .title {
          width: 602px;
          margin-right: 20px;
          font-size: 30px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #191f25;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .titleWidth {
          width: 600px;
          margin: 0 25px;
        }
      }
      .center {
        display: flex;
        justify-content: space-between;
        margin: 0 0 30px;
        p {
          margin: 0.2rem 0  0 0.34rem;
          font-size: 28px;
          display: flex;
          position: relative;
          .key {
            color: #888888;
            width: 2rem;
          }
          .value {
            color: #191f25;
            width: 240px;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .arrow {
            color: #1890ff;
            position: absolute;
            right: -10px;
          }
          /deep/.van-tag {
            margin-right: 10px;
            // width: 160px;
            flex-direction: column;
          }
        }
        .totalContain {
          margin-right: 10px;
          p {
            font-size: 24px;
          }
        }
      }
    }
  }
  .list {
    margin-top: 102px;
    .wrap {
      background: #fff;
      width: 100vw;
      .otherText {
        display: flex;
        justify-content: space-between;
        font-size: 32px;
        color: #191f25;
        margin: 0;
        font-weight: 500;
        .deleteStyle {
          font-weight: 400;
          color: #ff4d4f
        }
      }
      .top {
        display: flex;
        justify-content: flex-start;
        padding-top: 10px;
        .icon {
          width: 6px;
          height: 32px;
          background: #1890ff;
          margin: 6px 10px 0 10px;
        }
        .title {
          width: 602px;
          margin-right: 20px;
          font-size: 30px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #191f25;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .titleWidth {
          width: 600px;
          margin: 0 25px;
        }
      }
      .center {
        margin: 0 0 30px;
        p {
          margin: 6px 25px;
          font-size: 28px;
          display: flex;
          position: relative;
          .key {
            color: #888888;
          }
          .value {
            color: #191f25;
            width: 380px;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .arrow {
            color: #1890ff;
            position: absolute;
            right: -10px;
          }
          /deep/.van-tag {
            margin-right: 10px;
            // width: 160px;
            flex-direction: column;
          }
        }
      }
    }
  }
}

.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  overflow: scroll;
  padding: 20px 0;
  .formgroup {
    background: #ffffff;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
    .btncancle {
      width: 270px;
      margin: 0 30px;
      background: #f2f2f6;
      color: #1a2026;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
    }
  }
}
.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;
  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }
  /deep/ .van-field__control {
    max-width: 700px;
    // text-align: right;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;
  padding: 16px 0;
  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}
.required span::after {
  left: -20px;
  top: 3px;
}
.filedClear {
  width: 28px;
  height: 28px;
}
.formItemFlex {
  display: flex;
  flex-direction: row;
  .FormTit {
    flex: 1;
    min-width: 3.3rem;
    padding-top: 0.33rem;
  }
  .haveUnitBox {
    flex: 1;
    .van-cell {
      width: 6.2rem;
    }
  }
}
.list {
  margin-top: 10px;
  .wrap {
    background: #fff;
    width: 100vw;
    .otherText {
      display: flex;
      justify-content: space-between;
      font-size: 32px;
      font-weight: bold;
      color: #191f25;
      .deleteStyle {
        font-weight: 400;
        color: #ff4d4f
      }
    }
    .top {
      display: flex;
      justify-content: flex-start;
      padding-top: 10px;
      .icon {
        width: 6px;
        height: 32px;
        background: #1890ff;
        margin: 6px 10px 0 10px;
      }
      .title {
        width: 602px;
        margin-right: 20px;
        font-size: 30px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .titleWidth {
        width: 600px;
        margin: 16px 25px;
      }
    }
    .center {
      margin: 0 0 30px;
      p {
        margin: 6px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px;
        }
        /deep/.van-tag {
          margin-right: 10px;
          // width: 160px;
          flex-direction: column;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -30px;
        padding: 30px;
        margin-bottom: 30px;
      }
      .showAll2 {
        width: 100%;
        margin: 0 0 30px 0;
        padding: 30px 0;
      }
    }

  }
}
.d-head {
  width: 100%;
  padding: 32px;
  background: #ffffff;
  margin-bottom: 10px;
  .content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      flex: 1;
      .title {
        font-size: 32px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #191f25;
        line-height: 32px;

        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
      }
      .row {
        font-size: 28px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #888888;
        margin-top: 20px;
      }
    }
    .right {
      text-align: right;
      font-size: 26px;
      margin-top: 72px;
      .row {
        padding-top: 0px;
      }
      .warining {
        color: #fe9400;
      }
      .success {
        color: #4bd863;
      }
    }
  }
}
</style>
